import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.common.exceptions import TimeoutException
from taobao_check.tools import click_by_js
from .base import BaseBrush


class BaodanBear(BaseBrush):
    login_url = "http://baodanxiong.zhaoww.top:8001/business.php/user/login"
    index_url = "http://baodanxiong.zhaoww.top:8001/business.php/msg/getlist.html"
    check_url = "http://baodanxiong.zhaoww.top:8001/business.php/Selfaudit/index"

    def __init__(self, config, tab):
        super().__init__("爆单熊", "baodanbear", config, tab)

    def login(self):
        if self.browser.current_url != self.login_url:
            self.browser.get(self.login_url)

        self.enter_text((By.ID, "phone"), self.username)
        self.enter_text((By.ID, "password"), self.password)
        self.click_button((By.CSS_SELECTOR, "a[onclick]"))

        while self.browser.current_url != self.index_url:
            time.sleep(0.1)

        self.browser.get(self.check_url)

    def check_user(self):
        try:
            tr = self.find_element((By.CSS_SELECTOR, "tbody>tr"), timeout=3)
        except TimeoutException:
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False

        tds = tr.find_elements_by_tag_name("td")
        username = tds[6].get_attribute('textContent')
        username = username.strip().split()[0].strip()
        self.print_log(f"当前待验买号为：【{username}】")
        check_button = tds[7].find_element_by_tag_name("a")
        click_by_js(self.browser, check_button)

        start = time.time()
        result = self.check.check_user(username, self.print_log)
        self.print_log(f"验号结果为: {'通过' if result else '不通过'}. 用时: {time.time() - start:.2f}s")

        ok_button = (By.CSS_SELECTOR, "a.layui-layer-btn0")
        if not result:
            # 只有不通过才需要下拉框选择不通过
            box = self.find_element((By.CSS_SELECTOR, "div.layui-layer"))
            rematch = box.find_element_by_css_selector('dd[lay-value="0"]')
            click_by_js(self.browser, rematch)
            self.print_log("开始重新匹配买号.\n")
        self.click_button(ok_button)
        if result:
            self.print_log("开始任务.\n")

        self.sleep(2)
        return True
